package com.hna.iot.controller.business;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.hna.iot.base.BaseController;
import com.hna.iot.common.result.BaseResult;
import com.hna.iot.model.*;
import com.hna.iot.service.IIotProductService;

import org.apache.commons.lang.StringUtils;
import org.opentsdb.client.ExpectResponse;
import org.opentsdb.client.HttpClientImpl;
import org.opentsdb.client.request.QueryBuilder;
import org.opentsdb.client.request.SubQueries;
import org.opentsdb.client.response.SimpleHttpResponse;
import org.opentsdb.client.util.Aggregator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import sun.misc.BASE64Decoder;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class DeviceDataController extends BaseController {

	@Value("${photo_dir}")
	public  String photoDir;
	
	@Autowired
	IIotProductService dataService;
	
	public  HttpClientImpl client;
    @PostConstruct  
     public void init() {  
    	client = new HttpClientImpl("http://10.211.55.6:4242");
     }  
	

	

	private final static Logger log = LoggerFactory.getLogger(DeviceDataController.class);

	@RequestMapping("/data/index")
	public String index() {
		return "pages/data/index";
	}

	@RequestMapping("/data/add")
	public String add(HttpServletRequest request,String name) {
		request.setAttribute("name", name);
		return "pages/data/add";
	}

	

    @RequestMapping("/data/detail")
    public ModelAndView details(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("pages/data/detail");
        modelAndView.addObject("id", request.getParameter("id"));
        return modelAndView;
    }
    
    
    @RequestMapping("/data/edit")
	public ModelAndView edit(HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("pages/data/edit");
		modelAndView.addObject("id", request.getParameter("id"));
		return modelAndView;
	}

	@RequestMapping(value = { "/rest/data/list" }, method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> list(HttpServletRequest request, PageInfo pageInfo, IotProduct data,String dataName) {
		
//        


		
		Map<String, Object> res = new HashMap<>();
		try {
			QueryBuilder builder = QueryBuilder.getInstance();
	        SubQueries subQueries = new SubQueries();
	        String zimsum = Aggregator.zimsum.toString();
	        subQueries.addMetric("sys.cpu.nice").addTag("host", "web1").addTag("dc", "lga").addAggregator(zimsum).addDownsample("1s-" +
	                zimsum);;
	        long now = new Date().getTime() / 1000;
	        builder.getQuery().addStart(1499493542).addEnd(now).addSubQuery(subQueries);
	        
	        System.out.println(builder.build());
	        
	        SimpleHttpResponse response = client.pushQueries(builder,
                    ExpectResponse.STATUS_CODE);
	        
	        System.out.println(response.getContent());
            String content = response.getContent();
            System.out.println(response.getStatusCode());
            int statusCode = response.getStatusCode();
            
            int count=0;
            List dataList=new ArrayList();
            if (statusCode == 200) {
                JSONArray jsonArray = JSON.parseArray(content);
                System.out.println(jsonArray.toJSONString());
                for (Object object : jsonArray) {
                    JSONObject json = (JSONObject) JSON.toJSON(object);
                    String dps = json.getString("dps");
                    Map<String, String> map = JSON.parseObject(dps, Map.class);
                    
                    for (Map.Entry entry : map.entrySet()) {
                        System.out.println("Time:" + entry.getKey() + ",Value:" + entry.getValue());
                        
                        Date time=new Date(Long.parseLong(String.valueOf(entry.getKey()))*1000);
                        count++;
                    	Map showMap=new HashMap();
                        showMap.put("time", time);
                        showMap.put("value", entry.getValue());
                        dataList.add(showMap);
                    }
                    
                }
            }

			res.put("rows", dataList);
			res.put("total", count);
			res.put("success", "true");
			return res;
		} catch (Exception e) {
			log.error("",e);
			res.put("success", "false");
			return res;
		}
	}

	@RequestMapping("/rest/data/info")
	public @ResponseBody BaseResult info(HttpServletRequest request) {
		Long id = Long.parseLong(request.getParameter("id"));
		IotProduct data = dataService.selectById(id);
		return BaseResult.success(data);
	}

	@RequestMapping(value = { "/rest/data/del" }, method = RequestMethod.POST)
	public @ResponseBody BaseResult del(HttpServletRequest request, String ids) {
		try {

			if (StringUtils.isEmpty(ids)) {
				return BaseResult.success();
			}
			List<String> asList = Arrays.asList(ids.split(","));
			dataService.deleteBatchIds(asList);
//			for (String id: asList
//				 ) {
//				this.syninfo(Long.valueOf(id),2);
//			}
			return BaseResult.success();
		} catch (Exception e) {
			log.error("发生异常了", e);
			return BaseResult.fail(e.getMessage());
		}
	}

	@RequestMapping(value = { "/rest/data/add" }, method = RequestMethod.POST)
	public @ResponseBody BaseResult add(HttpServletRequest request, IotProduct data) {
		Map<String, Object> res = new HashMap<>();
		try {
//        	data.setMeterNo(meterNo);
			dataService.insert(data);

			return BaseResult.success();
		} catch (Exception e) {
			log.error("发生异常了", e);
			return BaseResult.fail(e.getMessage());
		}
	}

	@RequestMapping(value = { "/rest/data/update" }, method = RequestMethod.POST)
	public @ResponseBody BaseResult update(HttpServletRequest request, IotProduct data, String meterNo) {
		Map<String, Object> res = new HashMap<>();
		try {
//        	data.setMeterNo(meterNo);
			dataService.updateById(data);

			return BaseResult.success();
		} catch (Exception e) {
			log.error("发生异常了", e);
			return BaseResult.fail(e.getMessage());
		}
	}
	
	
	public void queryTest() throws IOException {
        HttpClientImpl client = new HttpClientImpl("http://10.211.55.6:4242");


        QueryBuilder builder = QueryBuilder.getInstance();
        SubQueries subQueries = new SubQueries();
        String zimsum = Aggregator.zimsum.toString();
        subQueries.addMetric("metric_fund").addTag("product", "HQD").addAggregator(zimsum).addDownsample("1s-" +
                zimsum);
        long now = new Date().getTime() / 1000;
        builder.getQuery().addStart(126358720).addEnd(now).addSubQuery(subQueries);
        System.out.println(builder.build());

        try {
            SimpleHttpResponse response = client.pushQueries(builder,
                    ExpectResponse.STATUS_CODE);
            String content = response.getContent();
            int statusCode = response.getStatusCode();
            if (statusCode == 200) {
                JSONArray jsonArray = JSON.parseArray(content);
                for (Object object : jsonArray) {
                    JSONObject json = (JSONObject) JSON.toJSON(object);
                    String dps = json.getString("dps");
                    Map<String, String> map = JSON.parseObject(dps, Map.class);
                    for (Map.Entry entry : map.entrySet()) {
                        System.out.println("Time:" + entry.getKey() + ",Value:" + entry.getValue());
                        Double.parseDouble(String.valueOf(entry.getValue()));
                    }
                }
            }
            //System.out.println(jsonArray);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
	
	
	

}
